package com.itljm.cxrMarket.security.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itljm.cxrMarket.mapper.SysRolePermissionMapper;
import com.itljm.cxrMarket.mapper.SysUserMapper;
import com.itljm.cxrMarket.entity.LoginUser;
import com.itljm.cxrMarket.entity.SysUser;
import com.itljm.cxrMarket.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author ljm
 * @date 2024/11/5 9:05
 */
@Service("sys_user")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper queryWrapper =  new QueryWrapper();
        queryWrapper.eq("username",username);
        //  1. 查询用户信息
        SysUser user = sysUserMapper.selectOne(queryWrapper);

        if(ObjectUtils.isNull(user)){
            throw new RuntimeException("用名名或者密码错误");
        }

        // 2. 获取用户权限
        List<String> permissions = getUserPermissions(user.getId());

        // 3. 返回自定义的 UserDetails 实现对象
        return new LoginUser(user,permissions);
    }

    private List<String> getUserPermissions(Long userId) {
        // 查询用户拥有的所有角色ID
        List<Long> roleIds = sysUserRoleMapper.selectRoleIdsByUserId(userId);

        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.emptyList();
        }

        // 根据角色ID查询所有权限
        List<String> permissions = sysRolePermissionMapper.selectPermissionsByRoleIds(roleIds);

        return permissions;
    }
}
